import Vue from 'vue'
import VueRouter from 'vue-router'
//导入路由
import login from '@/views/user/login.vue'
import home from '@/views/home/home.vue'
import qa from '@/views/qa/qa.vue'
import movie from '@/views/movie/movie.vue'
import user from '@/views/user/user.vue'
import edit from '@/views/user/edit.vue'
import layout from '@/views/layout.vue'
import notfound from '@/views/notfound/notfound.vue'
import article from '@/views/home/article.vue'
import search from '@/views/home/search.vue'
import searchResult from '@/views/home/searchResult.vue'
import student from '@/views/user/student.vue'



Vue.use(VueRouter)

const routes = [{
  name: 'login',
  path: '/login',
  component: login
}, {
  name: 'edit',
  path: '/edit',
  component: edit
}, {
  name: 'myarticle',
  path: '/article',
  component: article
}, {
  name: 'search',
  path: '/search',
  component: search
}, {
  name: 'searchResult',
  path: '/searchResult',
  component: searchResult
}, {
  name: 'student',
  path: '/student',
  component: student
},{
  name: 'layout',
  path: '/',
  component: layout,
  children: [{
    name: 'home',
    path: '/home',
    component: home
  }, {
    name: 'qa',
    path: '/qa',
    component: qa
  }, {
    name: 'movie',
    path: '/movie',
    component: movie
  }, {
    name: 'user',
    path: '/user',
    component: user,
    meta: {
      isLogin: true
    }
  }, {
    path: '/',
    redirect: '/home'
  }]
},
{
  path: '/notfound',
  name: 'notfound',
  component: notfound
}, {
  /* 
  (1)*:任意路径重定向到notfound
  (2)路由默认从上往下匹配的，如果可以匹配到则条抓页面，无法匹配则继续往下匹配直到所有路由结束
  */
  path: '*',
  redirect: '/notfound'
}
]

const router = new VueRouter({
  routes
})
//导入token工具包
import {
  getToken
} from '@/utils/token.js'
import {
  Toast
} from 'vant'

/* 注册路由前置导航守卫 */
router.beforeEach((to, from, next) => {
  // ...
  // to:去哪里 路由信息
  // from：从哪来 路由信息
  /* next :  必须要调用的，否则路由无法跳转 */
  //next() : 不传参，让你正常跳转（就是跳转目标路由to）
  //next({path:'路由路径'}) ： 进行拦截，不让你走（跳转到我指定路由）
  console.log(to);
  console.log(from);
  /* 并不是所有的页面都需要做登录判断，把需要登录判断的页面添加meta */

  //判断用户没有没有登录
  if (to.meta.isLogin) {
    //需要做登录判断
    if (getToken()) {
      //有登录，不拦截，允许正常跳转
      next()
    } else {
      //没有登录，进行拦截，跳转登录页
      Toast.fail('请先登录')
      next('/login')
      //3清除浏览器爆红提示
      setTimeout(() =>{
        console.clear()
      },1000);
    }
  } else {
    //不需要做登录判断，无条件跳转
    next()
  }
})
export default router
